<template>
  <div ref="box" :key="boxData.length" class="box-center">
    <template>
      <div
        v-for="(item,index) in boxData"
        :key="useKey(item,index)"
        :style="itemStyle"
        class="son"
        :class="hideSon(item.hideBox)"
        @click="$emit('item-click',item)"
      >
        {{ displayTextFun(item) }}
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: "BoxLeftCenter",
  props: {
    list: {
      type: Array,
      require: true,
      default: () => []
    },
    // 显示的文本
    displayTextFun: {
      type: Function,
      default: () => {},
      require: true
    },
    // 子元素样式
    itemStyle: {
      type: Object,
      default: () => {}
    },
    // key 绑定的字段
    keyField: {
      type: String,
      default: "value"
    },
    noDataText: {
      type: String,
      default: "暂无数据"
    },
    // 父元素padding (左右的padding 需要去除 )
    paddingW: {
      type: Number,
      default: 0
    },
    // 子元素左右的margin宽度
    sonMargin: {
      type: Number,
      default: 20
    }
  },
  data() {
    return {
      boxData: []
    };
  },
  created() {
    this.$nextTick(() => {
      this.boxData = this.list;
      this.boxData = this.polishingArr(this.boxData, this.$refs.box);
      console.log(this.boxData, "this.boxData");
    });
  },
  methods: {
    /**
     * @param {Array}   arr   需要补齐的数组
     * @param {dom}     ref   包裹数组的容器
     * @param {number}  width 容器中元素宽度
     * @returns 补齐数组长度(用于自适应布局)
   */
    polishingArr(arr = [], ref) {
      const { width } = this.itemStyle || {};
      if (!width) {
        console.log("子元素必须有宽度");
        return [];
      }

      // 子元素实际宽度
      const w = parseInt(width.replace("px", "")) + this.sonMargin;

      if (!ref || !arr.length) return [];
      // 盒子可使用宽度
      const allWidth = ref.offsetWidth - this.paddingW;
      // 每行可放置子盒子的个数
      const count = Math.floor((allWidth / w));
      // 当前子元素的个数
      const length = arr.length;
      // 补齐子元素的个数
      let refillQuantity = 0;
      if (count >= arr.length) {
        console.log(1);
        refillQuantity = count - length;
      } else {
        if ((arr.length % count) !== 0) {
          refillQuantity = count - (arr.length % count);
        }
      }

      // 对不显示的元素进行标记
      for (let i = 0; i < refillQuantity; i++) {
        arr.push({
          hideBox: "hide-box"
        });
      }
      return arr;
    },
    hideSon(flag) {
      return flag;
    },
    useKey(item, index) {
      return item?.keyField || index;
    }
  }
};
</script>
<style scoped lang="scss" src="./index.scss"></style>
